import React, { useState, useEffect,useRef } from "react";
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm/index'
import { Form ,Button,Image,Select,Divider,DatePicker, message} from 'antd';
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries} from 'redux/action'
import {getGraphList,getGraphDetailById} from 'api/index'
import classNames from "classnames";
import './index.scss'
import AddNewGame from 'components/AddNewGame'

import PreviewGame from 'components/LlxPreview/game'
const { RangePicker } = DatePicker;


function SubjectLibrary(props) {
const {dictionaries} = props
// 数据
const [loading,setLoading] = useState(false) //加载
const [total,setTotal] = useState(0) //总数量
const [isModalVisible, setIsModalVisible] = useState(false)
const [isModalVisiblePreview, setIsModalVisiblePreview] = useState(false)
const [id, setId] = useState('')
const [form] = Form.useForm();//搜索列表
const game = useRef(null)

//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})
// 表单数据
const formItem = [
  {label: '考点',type:'input', name: 'examination', span: 4 },
  {label: '创建人', name: 'createBy',  span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择创建人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '更新人', name: 'updateBy',  span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择更新人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '更新时间', name: 'updateTime', span: 7 ,render: () => {
    return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
}}
]
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
//表头配置信息
const columns = [
      {title: '考点', dataIndex: 'examination', key: 'examination', align: 'center'},
      {title: '封面', dataIndex: 'pictureUrl',width:150, key: 'pictureUrl', align: 'center',render:(text)=>{
        return  <div>
          {
            text?<Image
            width={60}
            src={text}
          />:''
          }
        </div>
      }},
      {title: '考点数', dataIndex: 'gameCircleCount', key: 'gameCircleCount', align: 'center'},
      {title: '创建人', dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
        return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
          {text}
       </div>
     }},
      {title: '更新人', dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
        return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {text}
     </div>
     }},
      {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:180},
      {title: '编辑', dataIndex: 'active', key: 'active', align: 'center',render:(text, record) => {
        return  <>
         <span onClick={()=>previewGame(record)} className="text-link">预览</span>&nbsp;&nbsp;&nbsp;&nbsp;
         <span onClick={()=>editGame(record)}  className="text-link">编辑</span>
        </>
      }}
]


// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='graph/graphLibrary')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='graph/graphLibrary')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps


// 切换发布草稿素材
useEffect(()=>{
  // 获取数据
  getNewList()
},[props.examineStatus]) // eslint-disable-line react-hooks/exhaustive-deps

// 方法
// 1.获取数据
const getNewList=(value)=>{

  setLoading(true)
  // 缓存数据
   const data = {
     pagination: value&&value.pageSize?value:pagination,
     form:form.getFieldValue()
  }
    props.setPageDataFn('graph/graphLibrary',data) 

    const initialData = async () => {

      const {
        createBy,
        endTime,
        examination,
        startTime,
        updateBy,
      } = form.getFieldValue()
      

      const params = {
        currPage:value&&value.pageSize?value.current:pagination.current,
        pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize,
        createBy,
        endTime,
        examination,
        startTime,
        updateBy,
        globalType:1
      }
     
        const res = await getGraphList(params)
        const data = res.result.records || []

        data.forEach((i,y)=>{
          i.sort =value&&value.pageSize?value.pageSize * (value.current - 1) + y + 1:pagination.pageSize * (pagination.current - 1) + y + 1
        })
        
        setDataSource(data)
  
        setTotal(res.result.total)
    

        setLoading(false)
    
    }
  
    initialData()
    }
 // 2.重置表单
 const resetForm=()=>{
   form.resetFields()
   setPagination({
    current:1,
    pageSize:20
  })
   getNewList()
 }
//  3.预览题目
const previewGame = (value) =>{
  setId(value.id+'?'+Math.random()*100)
  setIsModalVisiblePreview(true)
}
// 4.编辑题目
const editGame = async(value) => {
  setLoading(true)
 const res = await getGraphDetailById(value.id)

  game.current.form.setFieldsValue(res.result)

  game.current.form.setFieldsValue({
    gameItems:res.result.gameCircleDTO?.map((i,j) => {
      return {
        answers: i.answers.map(item => {
          return {
            circleId: item.circleId,
            coordinate: JSON.parse(item.coordinate)
          }
        }),
        pictureUrl: i.pictureUrl,
        examination: i.examination,
        audioUrl: i.audioUrl,
        correctError: i.correctError,
        wordId: i.wordId,
        gameId: i.gameId,
        sort:j+1,
        id: i.id,
        interfereAudio: i.interfereAudio,
        interfereText: i.interfereText
      }
    })||[]
  })
  setLoading(false)
 setIsModalVisible(true)

}
// 5.新增
const addNewGame = () => {
  game.current.setDataSource([])
  game.current.form.setFieldsValue({
      backgroundMusic: "",
      guideAudio: "",
      guideText: "",
      pictureUrl:'',
      analysisAudio:"",
      analysisText:"",
      id:'',
      gameItems:''
  })
  setIsModalVisible(true)
}

// 7.获取时间
const getUpdateTime = (value,dataString) => {
  const data = form.getFieldValue()
  data.startTime=dataString[0]
  data.endTime=dataString[1]
  form.setFieldsValue(data)
}
// 8.删除
const delGame = () => {
  message.error('删除功能待定')
}



return <div className="app-content animate__animated animate__fadeIn game">
    {/* 表单 */}
    <LlxForm form={form} formItem={formItem}/>

       {/* 操作按钮 */}
       <div className="operate-btn">
         <div>
         <Button  onClick={addNewGame} type='primary' className='animate__animated animate__fadeInLeft'>新增</Button>
         <Button  onClick={delGame}  disabled={!selectedRowKeys.length} type='primary' danger className='animate__animated animate__fadeInLeft'>删除</Button>
         </div>
         <div>
          <Button  onClick={getNewList} type='primary' className='animate__animated animate__fadeInRight'>查询</Button>
          <Button  type='primary' onClick={resetForm} className='animate__animated animate__fadeInRight'>重置</Button>
        </div>
    </div>

    <Divider />

    {/* 表格 */}
    <LlxTable
     loading={loading} 
     pagination={pagination}
     setPagination={setPagination}
     selectedRowShow={true}
     rowSelection={rowSelection.current}
     height={330}
     total={total}
     getNewList={getNewList}
     columns={columns}
     dataSource={dataSource}/>

  {/* 新增 */}
  <AddNewGame ref={game} userName={props.userInfo.user.userName} dictionaries={dictionaries} isModalVisible={isModalVisible} setIsModalVisible={setIsModalVisible}></AddNewGame>
  {/* 预览 */}
  <PreviewGame id={id} isModalVisible={isModalVisiblePreview} setIsModalVisible={setIsModalVisiblePreview}></PreviewGame>
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(SubjectLibrary)
